import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_baidu_mapapi_base/flutter_baidu_mapapi_base.dart';
import 'package:flutter_baidu_mapapi_map/flutter_baidu_mapapi_map.dart';
import 'package:flutter_baidu_mapapi_search/flutter_baidu_mapapi_search.dart';
import 'package:im_module/map/BMFBaseMapState.dart';
import 'package:im_module/model/LocationBean.dart';

class SelectMapAddressPage extends StatefulWidget {
  const SelectMapAddressPage();

  @override
  _SelectMapAddressPageState createState() => _SelectMapAddressPageState();
}

class _SelectMapAddressPageState extends BMFBaseMapState<SelectMapAddressPage> {
  List<BMFPoiInfo> mPoiInfoList = List.empty(growable: true);

  @override
  void initState() {
    super.initState();
    _requestLocaitonPermission();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void reassemble() {
    super.reassemble();
    _requestLocaitonPermission();
  }

  void _requestLocaitonPermission() async {
    /*PermissionStatus status = await Permission.location.request();
    print('permissionStatus=====> $status');*/
  }

  @override
  void onBMFMapCreated(BMFMapController controller) {
    super.onBMFMapCreated(controller);

    /// 地图渲染每一帧画面过程中，以及每次需要重绘地图时（例如添加覆盖物）都会调用此接口
    myMapController?.setMapOnDrawMapFrameCallback(
        callback: (BMFMapStatus mapStatus) {
//       print('地图渲染每一帧\n mapStatus = ${mapStatus.toMap()}');
        });

    /// 地图区域即将改变时会调用此接口
    /// mapStatus 地图状态信息
    myMapController?.setMapRegionWillChangeCallback(
        callback: (BMFMapStatus mapStatus) {
          print('地图区域即将改变时会调用此接口1\n mapStatus = ${mapStatus.toMap()}');
        });

    /// 地图区域改变完成后会调用此接口
    /// mapStatus 地图状态信息
    myMapController?.setMapRegionDidChangeCallback(
        callback: (BMFMapStatus mapStatus) {
          print('地图区域改变完成后会调用此接口2\n mapStatus = ${mapStatus.toMap()}');

          //搜索
          if (isSearch) {
            search(mapStatus.targetGeoPt.latitude,
                mapStatus.targetGeoPt.longitude);
          }
        });

    /// 地图区域即将改变时会调用此接口
    /// mapStatus 地图状态信息
    /// reason 地图改变原因
    myMapController?.setMapRegionWillChangeWithReasonCallback(callback:
        (BMFMapStatus mapStatus, BMFRegionChangeReason regionChangeReason) {
      print(
          '地图区域即将改变时会调用此接口3\n mapStatus = ${mapStatus
              .toMap()}\n reason = ${regionChangeReason.index}');
    });

    /// 地图区域改变完成后会调用此接口
    /// mapStatus 地图状态信息
    /// reason 地图改变原因
    myMapController?.setMapRegionDidChangeWithReasonCallback(callback:
        (BMFMapStatus mapStatus, BMFRegionChangeReason regionChangeReason) {
      print(
          '地图区域改变完成后会调用此接口4\n mapStatus = ${mapStatus
              .toMap()}\n reason = ${regionChangeReason.index}');

      isSearch = true;
    });
  }

  void citySearch() {
    // 构造检索参数
    BMFPoiCitySearchOption poiCitySearchOption = BMFPoiCitySearchOption(
        city: '$currentCity',
        keyword: '${_controller.text.toString()}',
        tags: ['小区', '楼', '编号'],
        pageSize: 20);
// 检索实例
    BMFPoiCitySearch poiCitySearch = BMFPoiCitySearch();
// 检索回调
    poiCitySearch.onGetPoiCitySearchResult(
        callback: (BMFPoiSearchResult result, BMFSearchErrorCode errorCode) {
          if (errorCode == BMFSearchErrorCode.RESULT_NOT_FOUND) {
            print("暂无数据");
            return;
          }
          if (errorCode == BMFSearchErrorCode.NO_ERROR) {
            List<BMFPoiInfo> poiList = result.poiInfoList;

            setState(() {
              mPoiInfoList.clear();
              mPoiInfoList.addAll(poiList);
            });

            if (poiList.isNotEmpty) {
              BMFPoiInfo  mBMFPoiInfo =  poiList[0];
              moveMap(mBMFPoiInfo.pt.latitude, mBMFPoiInfo.pt.longitude, false);
            }
          }
        });
    // 发起检索
    poiCitySearch.poiCitySearch(poiCitySearchOption);
  }

  void search(double? lat, double? lon) {
    BMFPoiNearbySearchOption poiNearbySearchOption = BMFPoiNearbySearchOption(
        keywords: <String>['小区', '楼', '编号'],
        location: BMFCoordinate(lat, lon),
        radius: 2000,
        pageSize: 20,
        isRadiusLimit: true);
    // 检索实例
    BMFPoiNearbySearch nearbySearch = BMFPoiNearbySearch();
    // 检索回调
    nearbySearch.onGetPoiNearbySearchResult(
        callback: (BMFPoiSearchResult result, BMFSearchErrorCode errorCode) {
          if (errorCode == BMFSearchErrorCode.RESULT_NOT_FOUND) {
            print("暂无数据");
            return;
          }
          if (errorCode == BMFSearchErrorCode.NO_ERROR) {
            setState(() {
              mPoiInfoList.clear();
              mPoiInfoList.addAll(result.poiInfoList);
            });
          }
        });
    nearbySearch.poiNearbySearch(poiNearbySearchOption);
  }

  void takeSnapshort() async {
    var image = await myMapController?.takeSnapshot();
  }

  TextEditingController _controller = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Container(
          height: 40,
          decoration: new BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(5.0)),
          ),
          alignment: Alignment.center,
          padding: EdgeInsets.fromLTRB(0.0, 0.0, 0.0, 0.0),
          child: TextField(
            controller: _controller,
            textInputAction: TextInputAction.search,
            decoration: InputDecoration(
              prefixIcon: Icon(Icons.search),
              border: InputBorder.none,
              hintText: "请输入内容",
              isDense: true,
            ),
            maxLines: 1,
            keyboardType: TextInputType.text,
            inputFormatters: <TextInputFormatter>[
              LengthLimitingTextInputFormatter(11) //限制长度
            ],
            onEditingComplete: () {
              var value = _controller.text;
              if (value.isEmpty) {
                print("输入内容不能为空");
                return;
              }
              citySearch();
              FocusScope.of(context).requestFocus(FocusNode());
            },
          ),
        ),
      ),
      body: ConstrainedBox(
        constraints: BoxConstraints.expand(),
        child: Column(
          children: [
            AspectRatio(
              aspectRatio: 1.1,
              child: Stack(
                children: [
                  generateMap(),
                  Center(
                    child: Icon(Icons.location_on,color: Colors.blue,size: 32),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(left: 15,bottom: 25),
                    child: Align(
                      alignment: Alignment.bottomLeft,
                      child: IconButton(
                          onPressed: (){
                            moveCurrentLocation();
                          }, icon: Icon(Icons.my_location,color: Colors.deepOrange,size: 28,),),
                    ),
                  )
                ],
              ),
            ),
            Expanded(flex: 1, child: buildContainer())
          ],
        ),
      ),
    );
  }

  Container buildContainer() {
    return Container(
      color: Colors.white,
      child: ListView.separated(
        itemCount: mPoiInfoList.length,
        separatorBuilder: (BuildContext context, int index) {
          return Divider(height: .5,);
        },
        itemBuilder: (context, int index) {
          BMFPoiInfo mBMFPoiInfo = mPoiInfoList[index];
          return ListTile(
            title: Text("${mBMFPoiInfo.name}"),
            subtitle: Text(
              "${mBMFPoiInfo.address}",
            ),
            onTap: () {
              Navigator.pop(
                  context,
                  LocationBean(
                      mBMFPoiInfo.pt.latitude,
                      mBMFPoiInfo.pt.longitude,
                      mBMFPoiInfo.city,
                      mBMFPoiInfo.name,
                      mBMFPoiInfo.address));
            },
          );
        },
      ),
    );
  }

/*void onMapCreated(AMapController controller) {
    _mapController = controller;
    */ /*setState(() {
      _mapController = controller;
      //getApprovalNumber();
    });*/ /*
  }*/

//移动地图结束
/*void _onCameraMoveEnd(CameraPosition cameraPosition) {
    */ /*setState(() {
      _currentZoom = '当前缩放级别：${cameraPosition.zoom}';
    });*/ /*

    print("当前经纬度:${cameraPosition.target.toString()}");

  }*/

/// 获取审图号
}
